package com.bawei.module_publish.openlive.ui

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.bawei.lib_common.base.BaseApplication
import com.bawei.lib_common.base.utils.LoggerUtils
import com.bawei.lib_mvi.base.BaseMVIFragment
import com.bawei.module_publish.databinding.DialogAddGoodsBinding
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.bawei.module_publish.R
import com.bawei.module_publish.databinding.FragmentCartGoodsBinding
import com.bawei.module_publish.databinding.FragmentMyGoodsBinding
import com.bawei.module_publish.openlive.adapter.GoodsAdapter
import com.bawei.module_publish.openlive.event.GoodsAddedEvent
import com.bawei.module_publish.openlive.event.GoodsCarEvent
import com.bawei.module_publish.openlive.intent.LiveIntent
import com.bawei.module_publish.openlive.model.entity.GoodRecord
import com.bawei.module_publish.openlive.model.entity.SquareGoodsBody
import com.bawei.module_publish.openlive.model.entity.TopCarBody
import com.bawei.module_publish.openlive.state.LiveState
import com.bawei.module_publish.openlive.viewmodel.LiveViewModel
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.launch
import com.bumptech.glide.Glide
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

private const val TAG = "AddGoodsDialog"
class AddGoodsDialog(val onGoodsSelected: (List<GoodRecord>) -> Unit) : BottomSheetDialogFragment() {
    private lateinit var binding: DialogAddGoodsBinding
    private val fragments = listOf(
        RecentGoodsFragment(),
        MyGoodsFragment(),
        CartGoodsFragment()
    )
    private var currentIndex = 1 // 默认"我的橱窗"
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DialogAddGoodsBinding.inflate(inflater, container, false)
        showFragment(currentIndex)
        bindingTab()
        // 其他底部全选、添加等逻辑可在Fragment中实现或在Dialog中实现
        return binding.root
    }

    override fun onStart() {
        super.onStart()
        dialog?.let {
            val bottomSheet = it.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
            bottomSheet?.layoutParams?.height = (resources.displayMetrics.heightPixels * 0.85).toInt()
            bottomSheet?.requestLayout()
        }
    }

    private fun bindingTab() {
        val tabViews = listOf(binding.tabRecent, binding.tabMy, binding.tabCart)
        tabViews.forEachIndexed { index, textView ->
            textView.setOnClickListener {
                showFragment(index)
                updateTabUI(index)
            }
        }
        updateTabUI(currentIndex)
    }

    private fun updateTabUI(selected: Int) {
        val tabViews = listOf(binding.tabRecent, binding.tabMy, binding.tabCart)
        tabViews.forEachIndexed { i, tv ->
            tv.setTextColor(if (i == selected) 0xFF222222.toInt() else 0xFF888888.toInt())
            tv.paint.isFakeBoldText = (i == selected)
        }
    }

    private fun showFragment(index: Int) {
        val fm = childFragmentManager
        val tag = "goods_tab_$index"
        val fragment = fragments[index]
        fm.commit {
            fragments.forEachIndexed { i, frag ->
                if (fm.findFragmentByTag("goods_tab_$i") != null) {
                    hide(frag)
                }
            }
            if (fm.findFragmentByTag(tag) == null) {
                add(binding.fragmentContainer.id, fragment, tag)
            }
            show(fragment)
        }
        currentIndex = index
    }
}

// 下面是三个Fragment的简单实现
class RecentGoodsFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_recent_goods, container, false)

        return view
    }
}

class MyGoodsFragment : BaseMVIFragment() {
    private lateinit var liveViewModel: LiveViewModel
    private val binding: FragmentMyGoodsBinding by lazy {
        FragmentMyGoodsBinding.inflate(layoutInflater)
    }
    private var goodList = mutableListOf<GoodRecord>()
    private val goodsAdapter: GoodsAdapter by lazy {
        GoodsAdapter(goodList) {
            val selectedCount = goodsAdapter.getSelectedCount()
            updateUi(selectedCount) // 更新 UI 显示
        }
    }
    override fun generateViewModel() {
        liveViewModel = ViewModelProvider(this)[LiveViewModel::class.java]
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        generateViewModel() // 保证ViewModel初始化
        setupAdapter() // 只初始化一次
        setupBottomBar()
        return binding.root
    }
    private fun updateUi(selectedCount: Int) {
        // 更新已选数量显示（假设布局中有 tvSelectedCount 控件）
        binding.tvSelectedCount.text = "$selectedCount/100"

        // 更新全选按钮状态
        binding.cbSelectAll.isChecked = selectedCount == goodsAdapter.itemCount
    }

    override fun lazyLoad() {}

    override fun initData() {
        super.initData()
        lifecycleScope.launch {
            liveViewModel.intents.send(LiveIntent.MyShowcase)
        }
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGoodsAdded(event: GoodsAddedEvent) {
        // 收到事件后刷新数据
        lifecycleScope.launch {
            liveViewModel.intents.send(LiveIntent.MyShowcase)
        }
    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return binding.root
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                liveViewModel._myGoodsNumFlow.collect {
                    when(it){
                        is LiveState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is LiveState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is LiveState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败${it.msg}")
                        }
                        is LiveState.GetGoodsSuccess -> {
                            Log.d(TAG, "handleState: ${it.msg}")
                            goodsAdapter.setData(it.msg.records)
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                liveViewModel._topCarFlow.collect {
                    when(it){
                        is LiveState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is LiveState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is LiveState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败${it.msg}")
                        }
                        is LiveState.TopCarSuccess -> {
                            Log.d(TAG, "handleState: ${it.msg}")
                            EventBus.getDefault().post(GoodsCarEvent)
                            // 网络请求成功后关闭弹窗
                            (parentFragment as? AddGoodsDialog)?.dismiss()
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
    }
    private fun setupAdapter() {
        binding.recyclerView.adapter = goodsAdapter
        binding.recyclerView.layoutManager = LinearLayoutManager(BaseApplication.instance)
    }
    private fun setupBottomBar() {
        // 全选CheckBox
        binding.cbSelectAll.setOnClickListener {
            val isAllSelected = binding.cbSelectAll.isChecked
            if (isAllSelected) {
                // 全选：将所有项加入选中集合
                for (i in 0 until goodsAdapter.itemCount) {
                    goodsAdapter.toggleSelection(i)
                }
            } else {
                // 取消全选：清空选中集合
                goodsAdapter.selectedSet.clear()
                goodsAdapter.notifyDataSetChanged()
            }
            updateUi(goodsAdapter.getSelectedCount())
        }
        // 添加按钮
        binding.btnAdd.setOnClickListener {
            val selectedItems = goodsAdapter.getSelectedItems()
            if (selectedItems.isEmpty()) {
                ToastUtils.showLong("请至少选择一件商品")
                return@setOnClickListener
            }
            // 拼接选中商品标题
//            val titles = selectedItems.joinToString(", ") { it.title }
//            ToastUtils.showLong(BaseApplication.instance,"已选商品：$titles")
            val topCarBody = TopCarBody(selectedItems[0].id.toString(), "285417033236483")
            lifecycleScope.launch {
                liveViewModel.intents.send(LiveIntent.TopCar(topCarBody))
            }
        }
    }

    override fun onResume() {
        super.onResume()
        lifecycleScope.launch {
            liveViewModel.intents.send(LiveIntent.MyShowcase)
        }
    }
}
class CartGoodsFragment : BaseMVIFragment() {
    private lateinit var liveViewModel: LiveViewModel
    private val binding: FragmentCartGoodsBinding by lazy {
        FragmentCartGoodsBinding.inflate(layoutInflater)
    }
    private var goodList = mutableListOf<GoodRecord>()
    private val goodsAdapter: GoodsAdapter by lazy {
        GoodsAdapter(goodList) {
            val selectedCount = goodsAdapter.getSelectedCount()
            updateUi(selectedCount) // 更新 UI 显示
        }
    }
    override fun generateViewModel() {
        liveViewModel = ViewModelProvider(this)[LiveViewModel::class.java]
    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        generateViewModel() // 保证ViewModel初始化
        setupAdapter() // 只初始化一次
        setupBottomBar()
        return binding.root
    }

    override fun initData() {
        super.initData()
        val squareGoodsBody = SquareGoodsBody(
            "",
            20,
            0,
            0,
            "",
            "",
            1
        )
        lifecycleScope.launch {
            liveViewModel.intents.send(LiveIntent.ChooseProductSquare(squareGoodsBody))
        }
    }

    override fun lazyLoad() {

    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return binding.root
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                liveViewModel._getSquareGoodsFlow.collect {
                    when(it){
                        is LiveState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is LiveState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is LiveState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败${it.msg}")
                        }
                        is LiveState.GetSquareGoodsSuccess -> {
                            Log.d(TAG, "handleState22: ${it.msg}")
                            goodsAdapter.setData(it.msg.records)
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                liveViewModel._addSquareGoodsFlow.collect {
                    when(it){
                        is LiveState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is LiveState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is LiveState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败${it.msg}")
                        }
                        is LiveState.AddOrCancelGoodsSuccess -> {
                            Log.d(TAG, "handleState22: ${it.msg}")
                            ToastUtils.showLong("添加成功")
                            // 添加成功后发送事件
                            EventBus.getDefault().post(GoodsAddedEvent)
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
    }
    private fun setupAdapter() {
        binding.recyclerView.adapter = goodsAdapter
        binding.recyclerView.layoutManager = LinearLayoutManager(BaseApplication.instance)
    }

    private fun updateUi(selectedCount: Int) {
        // 更新已选数量显示（假设布局中有 tvSelectedCount 控件）
        binding.tvSelectedCount.text = "$selectedCount/100"

        // 更新全选按钮状态
        binding.cbSelectAll.isChecked = selectedCount == goodsAdapter.itemCount
    }
    private fun setupBottomBar() {
        // 全选CheckBox
        binding.cbSelectAll.setOnClickListener {
            val isAllSelected = binding.cbSelectAll.isChecked
            if (isAllSelected) {
                // 全选：将所有项加入选中集合
                for (i in 0 until goodsAdapter.itemCount) {
                    goodsAdapter.toggleSelection(i)
                }
            } else {
                // 取消全选：清空选中集合
                goodsAdapter.selectedSet.clear()
                goodsAdapter.notifyDataSetChanged()
            }
            updateUi(goodsAdapter.getSelectedCount())
        }
        // 添加按钮
        binding.btnAdd.setOnClickListener {
            val selectedItems = goodsAdapter.getSelectedItems()
            if (selectedItems.isEmpty()) {
                ToastUtils.showLong("请至少选择一件商品")
                return@setOnClickListener
            }
//             拼接选中商品标题
//            val titles = selectedItems.joinToString(", ") { it.title }
//            ToastUtils.showLong(BaseApplication.instance,"已选商品：$titles")
            lifecycleScope.launch {
                liveViewModel.intents.send(LiveIntent.AddOrCancelShowcase(selectedItems[0].id))
            }
        }
    }

    override fun onResume() {
        super.onResume()
        val squareGoodsBody = SquareGoodsBody(
            "",
            20,
            0,
            0,
            "",
            "",
            1
        )
        lifecycleScope.launch {
            liveViewModel.intents.send(LiveIntent.ChooseProductSquare(squareGoodsBody))
        }
    }

}